package frame.system.mapper;

import frame.system.qo.AuthQo;
import frame.system.to.Role;
import org.apache.ibatis.annotations.*;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;
import java.util.Set;

/**
 * 对应表：sys_role 对于实体类：Role
 * <br>
 * @author PeiWentao
 * @since 2020-05-20 14:08
 */
public interface RoleMapper extends Mapper<Role> {

	// 字段
    String FIELDS = "t.name,t.shiro,t.description,t.valid,t.create_time,t.update_time,t.id";
    // 表名 as 别名
    String TABLE = "sys_role t";
    // mapper包名
    String PACKAGE = "frame.system.mapper";

    @Results({
        @Result(column = "id", property = "id",id = true),
        @Result(column = "id", property = "permissions", many = @Many(select = PACKAGE + ".PermissionMapper.allListByRoleId"))
    })
    @Select({"<script>SELECT ", FIELDS, " FROM ", TABLE,
            " WHERE t.valid=#{valid}",
            "<when test='name!=null'> AND name LIKE CONCAT('%',#{name},'%')</when>",
            "ORDER BY ${orderStr}",
            "</script>"})
	List<Role> pageList(AuthQo qo);
    // 根据用户ID级联查询角色
    @Select("SELECT t.name,t.shiro,t.id FROM " + TABLE + " WHERE t.valid=1 AND t.id in(SELECT rid FROM sys_user_2_role a WHERE a.uid=#{0})")
    List<Role> allListByUserId(Integer uid);

    // 根据用户名级联查询角色Shiro
    @Select("SELECT DISTINCT t.shiro FROM sys_role t JOIN sys_user_2_role r ON t.id = r.rid JOIN sys_user u ON u.id = r.uid WHERE u.username=#{0} AND t.valid='1'")
    Set<String> allShiroListByUsername(String username);

    @Insert({"<script>",
            "INSERT INTO sys_role_2_permission VALUES ",
            "<foreach collection='pids' item='pid' index='index' separator=','>",
            "(#{rid},#{pid})",
            "</foreach>",
            "</script>"})
    int addPermissions(@Param("rid") Integer roleId, @Param("pids") List<Integer> permissionIds);

    @Delete("DELETE FROM sys_role_2_permission WHERE rid = #{0}")
    int deletePermissions(Integer userId);
}
